<template>
  <el-dialog title="修改密码" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username" disabled placeholder="登录帐号"></el-input>
      </el-form-item>
        <el-form-item  label="密码" prop="password">
          <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="dataForm.confirmPassword" type="password" placeholder="确认密码"></el-input>
        </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="dataForm.newPassword" type="password" placeholder="确认新密码"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
const initUser = {
  username: '',
  password: '',
  confirmPassword: '',
  newPassword: ''
}
export default {
  name: 'Password',
  data () {
    const validateConfirmPassword = (rule, value, callback) => {
      if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      roleList: [],
      dataForm: { ...initUser },
      dataRule: {
        password: [
          { required: true, message: '原密码不能为空', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        newPassword: [{ required: true, message: '新密码不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    init (username) {
      this.visible = true
      this.dataForm = { ...initUser, username }
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$http.post('/sys/user/password', this.dataForm).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '修改密码成功，请重新登录！',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('closePassword')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
